<template>
  <div class="category-list-container">
    <!-- 搜索区域 -->
    <div class="search-card">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="分类名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入分类名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="分类层级">
          <el-select
            v-model="searchForm.level"
            placeholder="请选择分类层级"
            clearable
            style="width: 150px"
          >
            <el-option label="第1级" :value="1" />
            <el-option label="第2级" :value="2" />
            <el-option label="第3级" :value="3" />
            <el-option label="第4级" :value="4" />
            <el-option label="第5级" :value="5" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd()">
            <el-icon><Plus /></el-icon>
            新增分类
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="treeData"
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :default-expand-all="false"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="分类名称" min-width="200">
          <template #default="{ row }">
            <span class="category-name">
              <el-icon v-if="row.level === 1" color="#409EFF"><Folder /></el-icon>
              <el-icon v-else color="#67C23A"><FolderOpened /></el-icon>
              {{ row.name }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column label="层级" width="80">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)" size="small">
              第{{ row.level }}级
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="success" size="small" @click="handleAdd(row)">
              <el-icon><Plus /></el-icon>
              添加子分类
            </el-button>
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分类表单弹窗 -->
    <category-form
      v-model:visible="formVisible"
      v-model:category-data="currentCategory"
      v-model:parent-category="parentCategory"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Folder, FolderOpened } from '@element-plus/icons-vue'
import { getCategoryList, deleteCategory, buildCategoryTree } from '../../api/category'
import CategoryForm from './components/CategoryForm.vue'

// 搜索表单
const searchForm = reactive({
  name: '',
  level: null
})

// 表格数据
const treeData = ref([])
const loading = ref(false)

// 表单弹窗
const formVisible = ref(false)
const currentCategory = ref(null)
const parentCategory = ref(null)

// 获取层级标签样式
const getLevelTagType = (level) => {
  const typeMap = {
    1: 'danger',   // 第1级 - 红色
    2: 'warning',  // 第2级 - 橙色
    3: 'primary',  // 第3级 - 蓝色
    4: 'success',  // 第4级 - 绿色
    5: 'info'      // 第5级 - 灰色
  }
  return typeMap[level] || 'info'
}

// 获取分类列表
const fetchCategoryList = async () => {
  loading.value = true
  try {
    const params = { ...searchForm }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await getCategoryList(params)
    if (response.code === 200) {
      // 如果有搜索条件，直接显示平铺列表
      if (searchForm.name || searchForm.level) {
        treeData.value = response.data
      } else {
        // 否则构建树形结构
        treeData.value = buildCategoryTree(response.data)
      }
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  fetchCategoryList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    level: null
  })
  fetchCategoryList()
}

// 新增分类
const handleAdd = (parentRow = null) => {
  currentCategory.value = null
  parentCategory.value = parentRow
  formVisible.value = true
}

// 编辑分类
const handleEdit = (row) => {
  currentCategory.value = { ...row }
  parentCategory.value = null
  formVisible.value = true
}

// 删除分类
const handleDelete = async (row) => {
  // 检查是否有子分类
  if (row.children && row.children.length > 0) {
    ElMessage.warning('该分类下有子分类，不能删除')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除分类 "${row.name}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteCategory(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchCategoryList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 表单提交成功
const handleFormSuccess = () => {
  fetchCategoryList()
}

// 页面加载时获取数据
onMounted(() => {
  fetchCategoryList()
})
</script>

<style scoped>
.category-list-container {
  padding: 20px;
}

.search-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.table-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.category-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.el-table__expand-icon) {
  color: #409EFF;
}

:deep(.el-table__row--level-1 .el-table__expand-icon) {
  color: #409EFF;
}

:deep(.el-table__row--level-2 .el-table__expand-icon) {
  color: #67C23A;
}

:deep(.el-table__row--level-3 .el-table__expand-icon) {
  color: #E6A23C;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .category-list-container {
    padding: 15px;
  }
  
  .search-card {
    padding: 15px;
  }
  
  .table-card {
    padding: 15px;
  }
  
  :deep(.el-form--inline .el-form-item) {
    display: block;
    margin-bottom: 15px;
  }
  
  :deep(.el-form--inline .el-form-item__content) {
    margin-left: 0 !important;
  }
  
  :deep(.el-table .el-table__cell) {
    padding: 8px 0;
  }
}
</style>
